package com.qianfeng.front.interceptor;

import com.qianfeng.ls.anno.AuthCheckAnno;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //目标方法上面是否有注解;有注解才进行登录验证 ; handler 是方法,直接判断是否有注解; 是目标对象,得到方法

        //判断handler 是 handlermethod;
        if (handler instanceof HandlerMethod) {

            HandlerMethod hm = (HandlerMethod) handler;

            if (hm.hasMethodAnnotation(AuthCheckAnno.class)) { //当前的这个HandlerMethod是否有指定的注解把

                Object obj = request.getSession().getAttribute("customer");

                if(null == obj){
                    response.sendRedirect("login.jsp");
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
